<template>
  <div ref="mapContainer" class="map-container" />
</template>

<script setup>
import { ref, onMounted } from "vue";
import mapboxgl from "mapbox-gl";

const mapContainer = ref(null);
let map = null;

// 获取动态节点(网页9建议的负载均衡策略)
const getTDTNode = () => `https://t${Math.floor(Math.random() * 8)}.tianditu.global`;

// 矢量底图配置
const tdtLayers = {
  vector: {
    base: `${getTDTNode()}/vec_c/wmts?tk=YOUR_TOKEN&x={x}&y={y}&z={z}`,
    label: `${getTDTNode()}/cva_c/wmts?tk=YOUR_TOKEN&x={x}&y={y}&z={z}`,
  },
  satellite: {
    base: `${getTDTNode()}/img_c/wmts?tk=YOUR_TOKEN&x={x}&y={y}&z={z}`,
    label: `${getTDTNode()}/cia_c/wmts?tk=YOUR_TOKEN&x={x}&y={y}&z={z}`,
  },
};

onMounted(() => {
  mapboxgl.accessToken = "MAPBOX_ACCESS_TOKEN";

  map = new mapboxgl.Map({
    container: mapContainer.value,
    style: {
      version: 8,
      sources: {
        "tdt-vector": {
          type: "raster",
          tiles: [tdtLayers.vector.base],
          tileSize: 256,
        },
        "tdt-labels": {
          type: "raster",
          tiles: [tdtLayers.vector.label],
          tileSize: 256,
        },
      },
      layers: [
        { id: "base-layer", source: "tdt-vector", type: "raster" },
        { id: "label-layer", source: "tdt-labels", type: "raster" },
      ],
    },
    center: [116.40769, 39.90469], // 北京坐标系
    zoom: 10,
    projection: "gcj02", // 天地图2025新增投影支持（网页10）
  });

  // 添加自然资源专题层（网页10新特性）
  map.on("load", () => {
    map.addSource("natural-resources", {
      type: "geojson",
      url: `${getTDTNode()}/api/natural-resources`,
    });
    map.addLayer({
      id: "parks-layer",
      source: "natural-resources",
      type: "fill",
      paint: {
        "fill-color": "#00ff00",
        "fill-opacity": 0.5,
      },
    });
  });
});
</script>
